package org.jeecg.modules.paycenter.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.*;
import org.jeecg.modules.paycenter.exception.BankReceiveException;
import org.jeecg.modules.paycenter.exception.BankSendException;
import org.jeecg.modules.paycenter.pay.dto.PayResult;
import org.jeecg.modules.paycenter.pay.util.NhBankUtils;
import org.jeecg.modules.wlhy.bill.entity.HyDriverBill;
import org.jeecg.modules.wlhy.bill.service.IHyDriverBillService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverAccountBook;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverAccountBookService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author yangqf
 * @date 2023/6/25 9:19
 */
@Service
@Slf4j
public class ABCBankService {

    @Resource
    private IHyDriverAccountBookService hyDriverAccountBookService;
    @Resource
    private IHyDriverBankService hyDriverBankService;

    @Resource
    private IHyDriverBillService hyDriverBillService;

    public RespPacket getExchangeStatus(String billNum) {
        try {
            RespPacket exchangeStatus = NhBankUtils.getExchangeStatus(billNum);
            if(exchangeStatus == null){
                throw new JeecgBootException("查询交易状态失败");
            }
            return exchangeStatus;
        } catch (Exception e) {
            throw new JeecgBootException("查询交易状态失败");
        }
    }

    public PayResult getPayExchangeStatus(String billNum) {
        //查询交易状态
        String msg = "查询交易失败";
        String respSource = null;
        String respCode = null;
        try {
            RespPacket exchangeStatus = this.getExchangeStatus(billNum);
            if (exchangeStatus.isSuccess()) {
                String transSta = exchangeStatus.getTransSta();
                if ("4".equals(transSta)) {
                    return PayResult.ok();
                } else {
                    Cmp cmp = exchangeStatus.getCmp();
                    if (cmp != null) {
                        msg = cmp.getRespPrvData();
                    }
                    respSource = transSta;
                    respCode = "-1";
                }
            } else {
                respSource = "-2";
                respCode = "-1";
            }
        } catch (Exception e) {
            respSource = "-3";
            respCode = "-1";
            msg = e.getMessage();
        }
        return PayResult.error(respSource, respCode, msg);
    }

    public PayResult exchange(String billNum ,
                               String dbAccNo , String dbAccName, String dbLogAccNo, String dbProv ,
                               String crAccNo , String crAccName, String crProv,
                               BigDecimal amt , String postscript) {
        String msg = null;
        String respSource = null;
        String respCode = null;
        String rxtInfo = null;
        //支付
        try {
            RespPacket respPacket = NhBankUtils.insideExchange(
                    billNum, dbProv, crProv,
                    dbAccNo, dbLogAccNo, dbAccName,
                    crAccNo, crAccName, amt, postscript);
            if (respPacket.isSuccess()) {
                return PayResult.ok();
            } else {
                respSource = respPacket.getRespSource();
                respCode = respPacket.getRespCode();
                msg = respPacket.getRespInfo();
                rxtInfo = respPacket.getRxtInfo();
            }
        } catch (BankSendException e) {
            respSource = "5";
            respCode = "-1";
            msg = "发起交易超时，请重新支付";
        } catch (BankReceiveException e) {
            //查询交易状态
            respSource = "-2";
            respCode = "-2";
            msg = "接收报文超时，请重新支付";
        } catch (Exception e) {
            //查询交易状态
            respSource = "-1";
            respCode = "-1";
            msg = "交易失败，请重新支付";
        }
        return PayResult.error(respSource, respCode, msg, rxtInfo);
    }
    //endregion


    /**
     * 子账户之间余额调整
     * @param accNo
     * @param prov
     * @param amt
     * @param dbLogAccNo
     * @param crLogAccNo
     * @return
     * @throws Exception
     */
    public PayResult adjustAccountBookBalance(String accNo ,
                                              String prov ,
                                              BigDecimal amt ,
                                              String dbLogAccNo,
                                              String crLogAccNo,
                                              String postScript) throws Exception {


        String msg = null;
        String respSource = null;
        String respCode = null;
        String rxtInfo = null;
        //支付
        try {
            RespPacket respPacket = NhBankUtils.adjustAccountBookBalance(accNo, prov, amt, dbLogAccNo, crLogAccNo, postScript);
            if (respPacket.isSuccess()) {
                return PayResult.ok();
            } else {
                respSource = respPacket.getRespSource();
                respCode = respPacket.getRespCode();
                msg = respPacket.getRespInfo();
                rxtInfo = respPacket.getRxtInfo();
            }
        } catch (BankSendException e) {
            respSource = "5";
            respCode = "-1";
            msg = "发起交易超时，请重新支付";
        } catch (BankReceiveException e) {
            //查询交易状态
            respSource = "-2";
            respCode = "-2";
            msg = "接收报文超时，请重新支付";
        } catch (Exception e) {
            //查询交易状态
            respSource = "-1";
            respCode = "-1";
            msg = "交易失败，请重新支付";
        }
        return PayResult.error(respSource, respCode, msg, rxtInfo);
    }

    /**
     * 提现
     * @param driver
     * @param driverBankId
     * @param amt
     * @return
     */
    public Result tx(HyDriver driver , String driverBankId , BigDecimal amt){

        HyDriverAccountBook accountBook = hyDriverAccountBookService.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driver.getId())
        );
        if(accountBook == null){
            return Result.error("未获取到账户信息！");
        }
        //验证卡号
        HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
        if(driverBank == null){
            return Result.error("未获取到银行卡信息！");
        }
        if(!StringUtils.equals( driverBank.getDriverId() ,driver.getId())){
            return Result.error("银行卡信息错误！");
        }

        String crAccName = driverBank.getBankName();
        String crAccNo = driverBank.getBankNum();

        RespPacket packet = null;
        String accNo = accountBook.getAccNo();
        String logAccNo = accountBook.getLogAccNo();
        String lsd = CodeUtil.getBillNum();

        HyDriverBill driverBill = new HyDriverBill();
        driverBill.setBillNum(lsd);
        driverBill.setBillType("2");//提现
        driverBill.setDriverId(driver.getId());
        driverBill.setDbaccno(accNo);
        driverBill.setDbaccname(accountBook.getLogAccName());
        driverBill.setDblogaccno(logAccNo);
        driverBill.setCraccno(crAccNo);
        driverBill.setCraccname(crAccName);
        driverBill.setCrlogaccno("");
        driverBill.setAmt(amt); //提现金额
        driverBill.setRespSource("0");
        driverBill.setRespCode("4");
        driverBill.setRespInfo("交易成功");
        driverBill.setPayChannel("1");

        try {
            packet = NhBankUtils.tx(
                    lsd,accountBook.getProv(), "",
                    accNo, logAccNo, accountBook.getLogAccName(),
                    crAccNo, crAccName, amt,driverBank.getBankType());
            if(packet.isSuccess()){
                //添加司机流水单
                hyDriverBillService.save(driverBill);
                return Result.OK("操作成功！");
            }else {
                driverBill.setRespSource(packet.getRespSource());
                driverBill.setRespCode(packet.getRespCode());
                driverBill.setRespInfo(packet.getRespInfo());
                driverBill.setRxtInfo(packet.getRxtInfo());
            }
            //return Result.error(packet.getRespInfo());
        }  catch (BankSendException e) {
            return Result.error("发起交易超时,请重试！");
        } catch (BankReceiveException e) {
            //发送成功，但是接收数据后续处理异常
            driverBill.setRespSource("-1");
            driverBill.setRespCode("-1");
            driverBill.setRespInfo("接收交易数据超时,请查询交易状态");
            driverBill.setRxtInfo("");
        } catch (Exception e) {
            return Result.error("提现失败," + e.getMessage());
        }

        //查询交易状态
        RespPacket exchangeStatus = getExchangeStatus(lsd);
        String msg = "交易失败";
        if (exchangeStatus != null) {
            if (exchangeStatus.isSuccess()) {
                String transSta = exchangeStatus.getTransSta();
                if ("4".equals(transSta)) {
                    driverBill.setRespSource("0");
                    driverBill.setRespCode("4");
                    driverBill.setRespInfo("交易成功");
                    driverBill.setRxtInfo("");
                    hyDriverBillService.save(driverBill);
                    return Result.OK("操作成功！");
                }else {
                    Cmp cmp = exchangeStatus.getCmp();
                    if(cmp!=null){
                        msg = cmp.getRespPrvData();
                    }
                    driverBill.setRespSource(transSta);
                    driverBill.setRespInfo(msg);
                }
            }
        }
        hyDriverBillService.save(driverBill);
        return Result.error(msg);
    }
}
